package com.config.shiro;

import com.dao.common.UserMapper;
import com.entity.common.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Administrator on 2018/12/31.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        User user = userMapper.getUserByAccount(username);
        //根据用户名查询数据库
        //如果用户名不存在
        if(user==null){
            throw new UnknownAccountException();
        }
        //如果用户已经被锁定
        if("locked".equals(username)){
            throw new LockedAccountException();
        }
        ByteSource salt = ByteSource.Util.bytes(username);
        return new SimpleAuthenticationInfo(username,user.getPassword() ,salt, getName());
    }

    //角色权限和对应权限添加
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "sha-256";
        Object credentials = "123456";
        ByteSource admin = ByteSource.Util.bytes("admin");
        int hashIterations = 1024;
        SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, admin, hashIterations);
        System.out.println( simpleHash.toHex());
    }


}
